import router, { asyncRouter } from "@/router";
import { Message } from "element-ui";
import store from "@/store";

const whiteList = ["/login", "/auth-redirect"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // 从服务器获得
  const token = store.getters.token;
  const hasToken = !!token;
  console.log("beforeEach", "to:", to, "form:", from);
  // 根据角色动态添加路由
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        next();
      } else {
        try {
          const { roles } = await store.dispatch("user/getInfo");
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes",
            roles
          );

          // 使用 router.addRoute 替代 router.addRoutes
          accessRoutes.forEach((route) => {
            router.addRoute(route);
          });

          // 在 router 的新版本上，会有预期路由操作，对于回到原路由的地址，被检测为循环路由会报错
          // / => login => /
          // 确保路由添加完成后再跳转
          next({ ...to, replace: true });
          // router.push(to.path)  使用 push 方法不会被记录，也能解决错误问题
        } catch (error) {
        //   await store.dispatch("user/resetToken");

          console.log("error", error);
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  } else {
    // 白名单路由，不需要登录权限的，例如 login
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});
